package com.example.servlet;

import com.example.DAO.DBUtilsDAO;
import com.example.DAO.impl.DBUtilsFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet({"/deleteUser"})
public class DeleteUserServlet extends HttpServlet {
    private DBUtilsDAO dbConnection = DBUtilsFactory.getDBConnection();

    public DeleteUserServlet() {
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String sql = "DELETE FROM user WHERE user_name = ?";

        try {
            try (
                    Connection conn = this.dbConnection.getConnection();
                    PreparedStatement prepStmt = conn.prepareStatement(sql);
            ) {
                prepStmt.setString(1, username);
                int affectedRows = prepStmt.executeUpdate();
                if (affectedRows > 0) {
                    resp.sendRedirect("home.jsp");
                } else {
                    resp.sendRedirect("error.jsp");
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException("删除用户失败", e);
        }
    }
}
